package org.easy4j.framework.core.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Properties;

/**
 * @author bjliuyong
 * @version 1.0
 * @created date 15-11-9
 */
public class Config {

    public static final String CONF_NAME            = "easy4j.properties" ;

    public static final String PROJECT_CHARSET_NAME = "charset.name" ;
    public static final String PROJECT_BASE_PACKAGE = "base.package" ;

    public static final String DEFAULT_CHARSET_NAME = "UTF-8";
    public static final String  CHARSET_NAME        = getValue(PROJECT_CHARSET_NAME,DEFAULT_CHARSET_NAME) ;
    public static final Charset CHARSET             = Charset.forName(CHARSET_NAME);

    private Properties properties = new Properties();

    private Config(){

    }

    public static Config getInstance() {
        return  ConfigHolder.instance ;
    }

    public static String getValue(String key) {
        return ConfigHolder.instance.properties.getProperty(key) ;
    }

    public static String getValue(String key ,String defaultVal) {
        return ConfigHolder.instance.properties.getProperty(key ,defaultVal) ;
    }

    public static int getInt(String key) {
        return Integer.valueOf(getValue(key)) ;
    }

    public static int getInt(String key , int defaultVal) {

        if(ConfigHolder.instance.properties.contains(key)) {
            return getInt(key) ;
        }

        return defaultVal ;

    }

    public static void register(String key,String value ) {
        ConfigHolder.instance.properties.setProperty(key, value) ;
    }

    private void  load(InputStream inputStream ) throws IOException {
        properties.load(inputStream);
    }


    static class ConfigHolder {

        private static Logger LOG = LoggerFactory.getLogger(ConfigHolder.class) ;

        final static Config instance ;

        static {
            instance = new Config() ;
            load(CONF_NAME);
        }

        static void load( String configFile){
            InputStream inputStream = null;
            try {

                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

                if(classLoader == null )
                    classLoader = ConfigHolder.class.getClassLoader() ;

                inputStream = classLoader.getResourceAsStream(configFile);
                instance.load(inputStream);
            } catch (Exception e) {
                LOG.error("can not find easy4j.properties from classpath" ,e);
            } finally {
                if(inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        //no-op
                    }
                }
            }

        }
    }

    public static void printUsage() {

    }

}
